package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.controller.utils.R;
import com.itheima.domain.Book;
import com.itheima.service.IBookservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private IBookservice bookservice;

    @GetMapping
    public R getAll(){
        return new R(true,bookservice.list());
    }

    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
      /*  R r = new R();
        boolean flag = bookservice.save(book);
        r.setFlag(flag);*/
        if (book.getName().equals("123") )throw new IOException();
        boolean flag = bookservice.save(book);
        return new R(flag,flag ? "添加成功" : "添加失败");
    }

    @PutMapping
    public R updata(@RequestBody Book book){
        return new R(bookservice.updateById(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(bookservice.removeById(id));
    }

    @GetMapping("{id}")
    public R getByid(@PathVariable Integer id){
        return new R(true, bookservice.getById(id));
    }

   /* @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize){
        IPage<Book> page = bookservice.getPage(currentPage, pageSize);
        //如果当前页码值大于了总页码，重写查询
        if (currentPage > page.getPages()){
            page = bookservice.getPage((int)page.getPages(), pageSize);
        }
        return new R(true,page);

    }*/

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize,Book book){

        IPage<Book> page = bookservice.getPage(currentPage, pageSize,book);
        //如果当前页码值大于了总页码，重写查询
        if (currentPage > page.getPages()){
            page = bookservice.getPage((int)page.getPages(), pageSize,book);
        }
        return new R(true,page);

    }

}
